<template>
  <div class="menu-list">
    <a-card title="菜单管理" :bordered="false">
      <div class="action-area">
        <a-button type="primary" @click="handleAdd">
          <plus-outlined /> 新增菜单
        </a-button>
      </div>
      <a-table
        :columns="columns"
        :data-source="menuList"
        :loading="loading"
        :pagination="false"
        row-key="id"
        :expandable="{ defaultExpandAllRows: true }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'icon'">
            <component :is="getIcon(record.icon)" v-if="record.icon" />
            <span v-else>-</span>
          </template>
          <template v-else-if="column.key === 'type'">
            <a-tag :color="getTypeColor(record.type)">{{ record.typeName }}</a-tag>
          </template>
          <template v-else-if="column.key === 'status'">
            <a-tag :color="record.status === 1 ? 'green' : 'red'">{{ record.statusName }}</a-tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleAdd(record)">新增子菜单</a-button>
              <a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
              <a-popconfirm title="确定要删除这个菜单吗？" @confirm="handleDelete(record)">
                <a-button type="link" size="small" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
    <a-modal v-model:open="modalVisible" :title="modalTitle" @ok="handleModalOk" @cancel="handleModalCancel" width="800px">
      <a-form ref="formRef" :model="form" :rules="rules" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="上级菜单" name="parentId">
              <a-tree-select
                v-model:value="form.parentId"
                :tree-data="menuTreeData"
                :field-names="{ title: 'title', key: 'id', children: 'children' }"
                placeholder="请选择上级菜单"
                allow-clear
                tree-default-expand-all
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="菜单类型" name="type">
              <a-radio-group v-model:value="form.type">
                <a-radio :value="1">目录</a-radio>
                <a-radio :value="2">菜单</a-radio>
                <a-radio :value="3">按钮</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="菜单名称" name="title">
              <a-input v-model:value="form.title" placeholder="请输入菜单名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="菜单标识" name="name">
              <a-input v-model:value="form.name" placeholder="请输入菜单标识" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16" v-if="form.type !== 3">
          <a-col :span="12">
            <a-form-item label="路由地址" name="path">
              <a-input v-model:value="form.path" placeholder="请输入路由地址" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="组件路径" name="component" v-if="form.type === 2">
              <a-input v-model:value="form.component" placeholder="请输入组件路径" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="菜单图标" name="icon" v-if="form.type !== 3">
              <a-input v-model:value="form.icon" placeholder="请输入图标名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="权限标识" name="permission" v-if="form.type !== 1">
              <a-input v-model:value="form.permission" placeholder="请输入权限标识" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="显示排序" name="sort">
              <a-input-number v-model:value="form.sort" placeholder="请输入排序" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="菜单状态" name="status">
              <a-radio-group v-model:value="form.status">
                <a-radio :value="1">正常</a-radio>
                <a-radio :value="0">停用</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16" v-if="form.type === 2">
          <a-col :span="12">
            <a-form-item label="是否缓存" name="isCache">
              <a-radio-group v-model:value="form.isCache">
                <a-radio :value="1">缓存</a-radio>
                <a-radio :value="0">不缓存</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="是否显示" name="visible">
              <a-radio-group v-model:value="form.visible">
                <a-radio :value="1">显示</a-radio>
                <a-radio :value="0">隐藏</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item label="备注" name="remark">
          <a-textarea v-model:value="form.remark" placeholder="请输入备注" :rows="3" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import {
  MenuOutlined,
  PieChartOutlined,
  SettingOutlined,
  UserOutlined,
  PlusOutlined,
  HomeOutlined,
  TeamOutlined
} from '@ant-design/icons-vue'
import { getMenuTree, addMenu, updateMenu, deleteMenu } from '@/api/menu'

const loading = ref(false)
const menuList = ref([])
const modalVisible = ref(false)
const modalTitle = ref('新增菜单')
const formRef = ref()
const currentParent = ref(null)

const iconMap = {
  'MenuOutlined': MenuOutlined,
  'PieChartOutlined': PieChartOutlined,
  'SettingOutlined': SettingOutlined,
  'UserOutlined': UserOutlined,
  'PlusOutlined': PlusOutlined,
  'HomeOutlined': HomeOutlined,
  'peoples': TeamOutlined,
  'setting': SettingOutlined,
  'user': UserOutlined,
  'tree-table': MenuOutlined
}
const getIcon = (iconName) => iconMap[iconName] || HomeOutlined

const getTypeColor = (type) => {
  switch (type) {
    case 1: return 'blue'
    case 2: return 'green'
    case 3: return 'orange'
    default: return 'default'
  }
}

const form = reactive({
  id: '',
  parentId: null,
  name: '',
  path: '',
  component: '',
  icon: '',
  title: '',
  type: 1,
  permission: '',
  sort: 0,
  status: 1,
  isCache: 0,
  visible: 1,
  remark: ''
})

const columns = [
  { title: '菜单名称', dataIndex: 'title', key: 'title' },
  { title: '图标', dataIndex: 'icon', key: 'icon', width: 80 },
  { title: '排序', dataIndex: 'sort', key: 'sort', width: 80 },
  { title: '权限标识', dataIndex: 'permission', key: 'permission' },
  { title: '路由地址', dataIndex: 'path', key: 'path' },
  { title: '组件路径', dataIndex: 'component', key: 'component' },
  { title: '类型', dataIndex: 'type', key: 'type' },
  { title: '状态', dataIndex: 'status', key: 'status' },
  { title: '操作', key: 'action', width: 200 }
]

const rules = {
  title: [ { required: true, message: '请输入菜单名称', trigger: 'blur' } ],
  name: [ { required: true, message: '请输入菜单标识', trigger: 'blur' } ],
  type: [ { required: true, message: '请选择菜单类型', trigger: 'change' } ],
  sort: [ { required: true, message: '请输入排序', trigger: 'blur' } ],
  status: [ { required: true, message: '请选择菜单状态', trigger: 'change' } ]
}

const menuTreeData = computed(() => {
  const buildTreeData = (menus) => {
    return menus.map(menu => ({
      ...menu,
      children: Array.isArray(menu.children) ? buildTreeData(menu.children) : []
    }))
  }
  return buildTreeData(menuList.value)
})

const fixMenuChildren = (menuList) => {
  if (!Array.isArray(menuList)) return []
  return menuList.map(menu => ({
    ...menu,
    children: Array.isArray(menu.children) ? fixMenuChildren(menu.children) : []
  }))
}

const fetchMenuList = async () => {
  loading.value = true
  try {
    const res = await getMenuTree()
    menuList.value = fixMenuChildren(res.data.data || [])
  } catch (error) {
    message.error('获取菜单列表失败')
  } finally {
    loading.value = false
  }
}

const handleAdd = (record = null) => {
  modalTitle.value = record ? '新增子菜单' : '新增菜单'
  Object.assign(form, {
    id: '',
    parentId: record ? record.id : null,
    name: '',
    path: '',
    component: '',
    icon: '',
    title: '',
    type: 1,
    permission: '',
    sort: 0,
    status: 1,
    isCache: 0,
    visible: 1,
    remark: ''
  })
  currentParent.value = record
  modalVisible.value = true
}

const handleEdit = (record) => {
  modalTitle.value = '编辑菜单'
  Object.assign(form, record)
  modalVisible.value = true
}

const handleDelete = async (record) => {
  try {
    const res = await deleteMenu(record.id)
    if (res.data && res.data.code === 200) {
      message.success('删除成功')
      fetchMenuList()
    } else {
      message.error(res.data?.message || '删除失败')
    }
  } catch (error) {
    message.error('删除失败')
  }
}

const handleModalOk = async () => {
  try {
    await formRef.value.validate()
    let res
    if (form.id) {
      res = await updateMenu(form)
      if (res.data && res.data.code === 200) {
        message.success('更新成功')
      } else {
        message.error(res.data?.message || '更新失败')
        return
      }
    } else {
      res = await addMenu(form)
      if (res.data && res.data.code === 200) {
        message.success('添加成功')
      } else {
        message.error(res.data?.message || '添加失败')
        return
      }
    }
    modalVisible.value = false
    fetchMenuList()
  } catch (error) {
    message.error('表单提交失败')
  }
}

const handleModalCancel = () => {
  modalVisible.value = false
  formRef.value?.resetFields()
  currentParent.value = null
}

onMounted(() => {
  fetchMenuList()
})
</script>

<style scoped>
.menu-list {
  padding: 24px;
}
.action-area {
  margin-bottom: 16px;
}
@media (max-width: 600px) {
  .menu-list { padding: 4px !important; }
  .action-area { margin-bottom: 8px !important; }
  .ant-table { font-size: 12px !important; overflow-x: auto !important; min-width: 480px; }
  .ant-table-thead > tr > th,
  .ant-table-tbody > tr > td { padding: 4px 6px !important; }
  .ant-modal { width: 96vw !important; max-width: 96vw !important; min-width: 0 !important; }
}
</style> 